/*
 * @Author: 李琪 liqi@lark2game.com
 * @Date: 2024-12-07 10:57:20
 * @LastEditors: 李琪 liqi@lark2game.com
 * @LastEditTime: 2024-12-07 17:09:46
 * @FilePath: /cramped-room/assets/Script/Manager/TileMapManager.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { _decorator, Component, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc'
import { createUINode, RandomByRange } from '../Utils/UtilsIndex'
import { TileManager } from './TileManager'
import GameData from '../Runtime/GameData'
import ResourceManager from '../Runtime/ResourceManager'
const { ccclass, property } = _decorator
/* @author: seagull  @change:瓦片地图信息
 * @date: 2024/11/23 14:14 */

@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    console.log(ResourceManager.Instance)
    console.log(GameData.Instance)
    try {
      const tileMapSpriteFrame = await ResourceManager.Instance.loadAtlasAsync('tile')
      const { mapInfo } = GameData.Instance
      console.log(tileMapSpriteFrame)
      for (let i = 0; i < mapInfo.length; i++) {
        const row = mapInfo[i]
        for (let j = 0; j < row.length; j++) {
          const tileItem = row[j]
          if (tileItem.src == null || tileItem.type == null) {
            continue
          }
          const tileNode = createUINode(`tileNode_${i}_${j}`)
          //随机生成地图
          let number = tileItem.src
          if ((number == 1 || number == 5 || number == 9) && i % 2 == 0 && j % 2 == 0) {
            number += RandomByRange(0, 4)
          }

          const imgSrc = `tile (${number})`
          const tileSpriteFrame = tileMapSpriteFrame.getSpriteFrame(imgSrc) || tileMapSpriteFrame[0]

          const tileManager = tileNode.addComponent(TileManager)
          tileManager.init(tileSpriteFrame, i, j)

          tileNode.setParent(this.node)
        }
      }
    } catch (error) {
      console.error('Error loading tile map:', error)
    }
  }
}
